package com.ai5suoai.ams.security;

import com.ai5suoai.ams.entity.User;
import com.ai5suoai.ams.service.UserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author chenzhenjia
 * @since 16/3/31
 */
@Component
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
    @Autowired
    UserService userService;
    private Logger logger = LoggerFactory.getLogger(UserDetailsService.class);

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("{} 用户登陆", username);
        String lowerUsername = username.toLowerCase();
        Optional<User> userFromDatabase = userService.findOneByUsername(lowerUsername);
        return userFromDatabase.map(user -> {
            if (!user.isActivated()) {
                logger.info("{} 用户没有激活", username);
                throw new RuntimeException("该用户没有激活");
            }
            List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
                    .map(authority -> new SimpleGrantedAuthority(authority.getName()))
                    .collect(Collectors.toList());
            return new org.springframework.security.core.userdetails.User(lowerUsername,
                    user.getPassword(),
                    grantedAuthorities);
        }).orElseThrow(() -> new UsernameNotFoundException("用户名 " + username + " 不存在"));
    }
}
